<?php

namespace app\admin\controller;

use app\BaseController;
use app\Request;
use app\admin\Validate;
use services\adminUser\model\AdminUser;
use app\admin\middleware\Login as LoginMiddleware;
use app\service\token\TokenStore;
use app\admin\service\AdminUserManger;
use app\admin\service\Token;
class Login extends BaseController{

    const KEY = "admin_login";
    function index()
    {
        return view("/login");
    }

    function post(Request $req)
    {
        $data = $req->only(['username','password']);
        $v = $this->postVali();
        if(!$v->check($data)){
            return error_json($v->getError());
        }
        /** @var AdminUser */
        $user = app(AdminUserManger::class)->findByUsername($data['username']);
        if(!$user || !app(AdminUserManger::class)->checkPassword($data['password'],$user['password'])){
            return error_json("用户名或密码错误");
        }elseif($user['state'] != 0){
            return error_json('该用户已被禁止登录');
        }
        /** @var Token $tokenStore */
        $tokenStore = app(Token::class);
        $token = $tokenStore->storeToken($user['id'],3600,'admin',[
           'username'=>$user['username'],
           'user_id'=>$user['id'],
        ]);
        return success_json("登录成功",[
            "url"=>''.admin_url('/')
        ])->cookie('token',$token['token']);
    }
    
    protected function postVali()
    {
        return new class extends Validate{
            protected $rule = [
                'username'  =>  'require|max:32',
                'password' =>  'require|max:64',
            ];
            protected $message = [
                'username.require'=>"用户或密码不正确",
                'password.require'=>"用户或密码不正确",
                'username.max'=>"用户名输入过长",
                'username.max'=>"密码输入过长",
            ];
        };
    }
}